import { BadGatewayException, Body, Controller, Get, Ip, Post, Query, Req, UseGuards, UseInterceptors } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { ModelType } from '@typegoose/typegoose/lib/types';
import { InjectModel } from 'nestjs-typegoose';
import { User } from 'src/decorator/user.decorator';
import { BaoMinModel } from 'src/mongodb/models/baominModel/BaoMinModel';
import { QudaobaoModel } from 'src/mongodb/models/qudaobaoModel/qudaobaoModel';
import { JobModel } from 'src/mongodb/models/jobModel/Job.models';
import { UserModel } from 'src/mongodb/models/userModel/User.models';
import { LanxiModel } from 'src/mongodb/models/lianxiModel/LanxiModel';
import * as crypto from 'crypto'
import { JihuoModel } from 'src/mongodb/models/jihuoModel/jihuoModel';
import { WorkInterceptor } from './work.interceptor';
import { RedisdbService } from 'src/redis/redisdb.service';
import { IdfaModel } from 'src/mongodb/models/idfaModel/idfa.models';

@Controller('index')
export class WorkController {
    constructor(
        @InjectModel(JobModel) private jobModel: ModelType<JobModel>,
        @InjectModel(BaoMinModel) private readonly baoMin: ModelType<BaoMinModel>,
        @InjectModel(QudaobaoModel) private readonly qudaobao: ModelType<QudaobaoModel>,
        @InjectModel(LanxiModel) private readonly lianxi: ModelType<LanxiModel>,
        @InjectModel(JihuoModel) private readonly jihuo: ModelType<JihuoModel>,
        private redis: RedisdbService
    ) { }



    /* 查询兼职列表 */
    @Get('getWorkList')
    @UseInterceptors(WorkInterceptor)
    async getWorkList(@Query() query, @Req() req) {
        try {
            const qudaobao = await this.qudaobao.findOne({ mark: req.dns })

            if (qudaobao) {
                if (!qudaobao.qudaohide) {
                    if (req.isProvince) {
                        if (qudaobao) {
                            return { data: await this.jobModel.find({ fake: qudaobao.fake, checkedCities: { $elemMatch: { $eq: query.type } } }, ['title', 'price', 'unit', 'settlement', 'jobTime', 'jobAddress', 'jobNum', 'companyData']).sort({ 'sort': -1 }), code: 200 }
                        }
                    }
                    return { data: await this.jobModel.find({ fake: 0, checkedCities: { $elemMatch: { $eq: query.type } } }, ['title', 'price', 'unit', 'settlement', 'jobTime', 'jobAddress', 'jobNum', 'companyData']).sort({ 'sort': -1 }), code: 200 }
                } else {
                    try {
                        if (query.imei) {
                            let result: IdfaModel
                            let imeiData = JSON.parse(query.imei)
                            if (query.platform == 'android') {
                                if (imeiData.oaid) {
                                    result = await this.redis.exists(imeiData.oaid.toLowerCase() + "_" + req.dns)
                                    if (!result) {
                                        if (imeiData.imei) await md5imei.call(this)
                                    }
                                } else if (imeiData.imei) {
                                    await md5imei.call(this)
                                }
                                async function md5imei() {
                                    const imei: string[] = imeiData.imei.split(",")
                                    for (let item of imei) {
                                        const md5 = crypto.createHash('md5');
                                        result = await this.redis.exists(md5.update(item).digest('hex') + "_" + req.dns);
                                        if (result) break;
                                    }
                                }
                            }
                            if (query.platform == 'ios') {
                                if (imeiData.idfa) {
                                    result = await this.redis.exists(imeiData.idfa.toLowerCase() + "_" + req.dns)
                                }
                            }
                            if (result) {
                                if (req.isProvince) {
                                    if (qudaobao) {
                                        return { data: await this.jobModel.find({ fake: qudaobao.fake, checkedCities: { $elemMatch: { $eq: query.type } } }, ['title', 'price', 'unit', 'settlement', 'jobTime', 'jobAddress', 'jobNum', 'companyData']).sort({ 'sort': -1 }), code: 200 }
                                    }
                                }
                            }
                        }
                        return { data: await this.jobModel.find({ fake: 0, checkedCities: { $elemMatch: { $eq: query.type } } }, ['title', 'price', 'unit', 'settlement', 'jobTime', 'jobAddress', 'jobNum', 'companyData']).sort({ 'sort': -1 }), code: 200 }
                    } catch (error) {
                        console.log(error);
                        throw new BadGatewayException(error)
                    }
                }
            } else {
                throw new BadGatewayException('请下载合法app')
            }
        } catch (error) {
            throw new BadGatewayException(error)
        }
    }



    /**
    * @Description: 随机返回列表
    * @return: Promise
    */
    @Get('randomGetWorkList')
    async randomGetWorkList(@Req() req) {
        try {
            const qudaobao = await this.qudaobao.findOne({ mark: req.dns })
            let userlist = await this.jobModel.aggregate([
                {
                    /* 条件 */
                    "$match": {
                        fake: qudaobao.fake,
                        sort: { $gt: 3 }
                    }
                },
                { $sample: { size: 5 } }
            ])

            return { data: userlist, code: 200 }

        } catch (error) {
            throw new BadGatewayException(error)
        }
    }




    /* 查询兼职详情 */
    @Post('getWorkDetails')
    async getWorkDetails(@Body() body, @Req() req) {
        try {
            /* 查询有没有报名记录,或者收藏记录 */
            let baomindata: any = await this.baoMin.findOne({ userid: body.userid, jobid: body.id });
            if (!baomindata) {
                /* 没有记录直接查询该数据库 */
                baomindata = await this.jobModel.findOne({ _id: body.id }, ['title', 'price', 'unit', 'settlement', 'jobIntr', 'jobTime', 'jobAddress', 'jobNum', 'companyData', 'fake'])
            }
            /* 判断该兼职包是否是虚假职位 */

            if (baomindata.fake != 0) {

                if (body.imei) {
                    const md5 = crypto.createHash('md5');
                    const imeimd5 = md5.update(body.imei).digest('hex')
                    this.jobModel.updateOne({ _id: body.id }, { $inc: { cumulativeclick: 1, clicktoday: 1 } }).then()

                    const channelResult = await this.qudaobao.findOne({ mark: req.dns })

                    /* 判断联系方式是否去重 */
                    if (channelResult.deduplication) {
                        /* 查询该设备信息 */
                        const jihuolianxi: any = await this.jihuo.findOne({ imeiMd5: imeimd5, ditch: req.dns, type: 'jihuo' })
                        /* 判断该设备是否存在 */
                        if (jihuolianxi) {
                            /* 设备信息存在,判断设备是否绑定成功联系方式 */
                            if (jihuolianxi.lianxi) {
                                // ============================================
                                /* 判断联系方式是否为客服系统,如果是客服系统,不会再获取新的联系方式给用户 */
                                if (jihuolianxi.lianxi.type != 5) {
                                    /* 查询绑定的联系方式是否存在,如果存在返回联系方式,如果不存在则获取新的联系方式给用户 */
                                    const lianxi = await this.lianxi.findOne({ _id: jihuolianxi.lianxi['_id'], status: true })
                                    if (!lianxi) {
                                        const newlianxi = await this.lianxi.findOne({ mark: req.dns, status: true }).sort({ devnum: 1 })
                                        if (newlianxi) {
                                            this.jihuo.updateOne({ _id: jihuolianxi._id }, { lianxi: newlianxi }).then()
                                            this.lianxi.updateOne({ _id: newlianxi._id }, { $inc: { devnum: 1 } }).then()
                                            return {
                                                code: 200,
                                                data: baomindata, contact: {
                                                    id: newlianxi._id,
                                                    contact: newlianxi.contact,
                                                    type: newlianxi.type
                                                }
                                            }
                                        }
                                        return {
                                            code: 200,
                                            data: baomindata, contact: {
                                                contact: '今日报名已满',
                                                type: 4
                                            }
                                        }

                                    }
                                }
                                // ============================================
                                return {
                                    code: 200,
                                    data: baomindata, contact: {
                                        id: jihuolianxi.lianxi._id,
                                        contact: jihuolianxi.lianxi.contact,
                                        type: jihuolianxi.lianxi.type
                                    }
                                }
                            } else {
                                /* 设备没有绑定好联系方式,查询联系方式 */
                                const lianxi = await this.lianxi.findOne({ mark: req.dns, status: true }, ['contact', 'type']).sort({ todaycopy: -1 });
                                /* 判断数据库是否存再联系方式 */
                                if (lianxi) {
                                    this.jihuo.updateOne({ _id: jihuolianxi._id }, { lianxi }).then();
                                    this.lianxi.updateOne({ _id: lianxi._id }, { $inc: { devnum: 1 } }).then()
                                    return {
                                        code: 200,
                                        data: baomindata, contact: {
                                            id: lianxi._id,
                                            contact: lianxi.contact,
                                            type: lianxi.type
                                        }
                                    };
                                }
                            }
                        }
                    } else {

                        const newlianxi = await this.lianxi.findOne({ mark: req.dns, status: true }).sort({ devnum: 1 })
                        if (newlianxi) {
                            await this.lianxi.updateOne({ _id: newlianxi._id }, { $inc: { devnum: 1 } })
                            return {
                                code: 200,
                                data: baomindata, contact: {
                                    id: newlianxi._id,
                                    contact: newlianxi.contact,
                                    type: newlianxi.type
                                }
                            }
                        }
                        return {
                            code: 200,
                            data: baomindata, contact: {
                                contact: '今日报名已满',
                                type: 4
                            }
                        }
                    }
                }

                /* 判断浏览器是否访问联系方式 */
                if (process.env.WEB == 'true') {
                    const newlianxi = await this.lianxi.findOne({ mark: req.dns, status: true }).sort({ devnum: 1 })

                    if (newlianxi) {
                        await this.lianxi.updateOne({ _id: newlianxi._id }, { $inc: { devnum: 1 } })
                        return {
                            code: 200,
                            data: baomindata, contact: {
                                id: newlianxi._id,
                                contact: newlianxi.contact,
                                type: newlianxi.type
                            }
                        }
                    }
                }

            } else {

                const ipone = [
                    '17701897543', "13120398285", "15123184425", "15520954745", "13161851166", "13430257838", "18423217078", "18423217078", "13331075136", "17172129711", "17347971226",
                ];
                return {
                    code: 200,
                    data: baomindata, contact: {
                        contact: ipone[Math.floor(Math.random() * ipone.length)],
                        type: 3
                    }
                }
            }
            return {
                code: 200,
                data: baomindata, contact: {
                    contact: '今日报名已满',
                    type: 4
                }
            }
        } catch (error) {
            console.log(error);
            throw new BadGatewayException(error)
        }
    }


    /**
    * @Description: 查询报名列表
    * @return: Promise
    */
    @Get('entryWorkList')
    @UseGuards(AuthGuard("jwt"))
    async entryWorkList(@User() user: UserModel) {
        try {
            const entrylist = await this.baoMin.find({ userid: user._id, isBaoMin: true })
            return { code: 200, data: entrylist }
        } catch (error) {
            throw new BadGatewayException(error)
        }
    }


    /* 取消报名 */
    @Post('cancelEntryWork')
    @UseGuards(AuthGuard("jwt"))
    async cancelEntryWork(@Body() body, @User() user: UserModel) {
        try {
            await this.baoMin.updateOne({ userid: user._id, jobid: body.id }, { isBaoMin: false })
            return { message: "取消报名成功", code: 200 }
        } catch (error) {
            throw new BadGatewayException(error)
        }
    }


    /* 点击收藏 */
    @Post('collect')
    @UseGuards(AuthGuard("jwt"))
    async collect(@Body() body, @User() user: UserModel) {
        try {
            const baoMinResult = await this.baoMin.findOne({ userid: user._id, jobid: body.id })
            if (baoMinResult) {
                await this.baoMin.updateOne({ userid: user._id, jobid: body.id }, { isCollect: true })
                return { message: "收藏成功", code: 200 }
            } else {
                const joblist = await this.jobModel.findOne({ _id: body.id }, ['title', 'price', 'unit', 'settlement', 'jobIntr', 'jobTime', 'jobAddress', 'jobNum', 'companyData', 'fake'])
                await this.baoMin.create({
                    title: joblist.title,
                    price: joblist.price,
                    unit: joblist.unit,
                    settlement: joblist.settlement,
                    jobIntr: joblist.jobIntr,
                    jobTime: joblist.jobTime,
                    jobAddress: joblist.jobAddress,
                    jobNum: joblist.jobNum,
                    companyData: joblist.companyData,
                    isCollect: true,
                    isBaoMin: false,
                    jobid: body.id,
                    userid: user._id,
                    fake: joblist.fake
                })
                return { message: "收藏成功", code: 200 }
            }
        } catch (error) {
            throw new BadGatewayException(error)
        }
    }


    /**
    * @Description: 收藏列表
    * @return: Promise
    */
    @Get('collectList')
    @UseGuards(AuthGuard("jwt"))
    async collectList(@User() user: UserModel) {
        try {
            const entrylist = await this.baoMin.find({ userid: user._id, isCollect: true })
            return { code: 200, data: entrylist }

        } catch (error) {
            throw new BadGatewayException(error)
        }
    }



    /* 取消收藏 */
    @Post('cancelCollect')
    @UseGuards(AuthGuard("jwt"))
    async cancelCollect(@Body() body, @User() user: UserModel) {
        try {
            await this.baoMin.updateOne({ userid: user._id, jobid: body.id }, { isCollect: false })
            return { message: "取消收藏成功", code: 200 }
        } catch (error) {
            throw new BadGatewayException(error)
        }
    }




    /* 限制包 */
    @Get('isDevice')
    async isDevice(@Req() req) {
        try {
            const qudaobao = await this.qudaobao.findOne({ mark: req.dns })
            if (qudaobao) {
                return true
            } else {
                return false
            }
        } catch (error) {
            throw new BadGatewayException(error)
        }
    }
}
